﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace ArienToolkits.MVC4.Attributes
{
    /// <summary>
    /// 防重复提交特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class VerifyRepeatSubmitAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string httpMethod = filterContext.RequestContext.HttpContext.Server.HtmlEncode(filterContext.RequestContext.HttpContext.Request.HttpMethod);

            //如果提交方法是POST提交方法
            if (string.Equals(httpMethod, "POST", StringComparison.CurrentCultureIgnoreCase))
            {
                string cacheToken = filterContext.HttpContext.Request["ArienToolkits_VerifyRepeatSubmit"];

                //如果含有提交验证戳
                if (!string.IsNullOrEmpty(cacheToken))
                {
                    //如果缓存中不包含提交戳信息，则代表可以提交
                    if (HttpContext.Current.Cache[cacheToken] == null)
                    {
                        //设置时间戳，五分钟后失效
                        HttpContext.Current.Cache.Insert(cacheToken, cacheToken, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0));
                    }
                    else
                    {
                        RouteValueDictionary dict = new RouteValueDictionary();
                        dict["controller"] = filterContext.RequestContext.RouteData.Values["controller"];
                        dict["action"] = filterContext.RequestContext.RouteData.Values["action"]; ;

                        filterContext.Result = new RedirectToRouteResult(dict);
                    }
                }
            }
        }
    }
}
